package com.yilin.tms.order.service.party.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.util.JsonUtil;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.entity.gps.VehicleGps;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.party.OrderSpecialApply;
import com.yilin.tms.core.entity.order.rob.RobOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.truck.TruckVehicle;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.UserAccrual;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.remote.IGpsRemote;
import com.yilin.tms.order.mapper.party.SpecialApplyMapper;
import com.yilin.tms.order.service.order.IGoodsService;
import com.yilin.tms.order.service.order.IRobService;
import com.yilin.tms.order.service.order.ITransitService;
import com.yilin.tms.order.service.party.IOrderAutLogService;
import com.yilin.tms.order.service.party.ISpecialApplyService;
import com.yilin.tms.order.service.payment.IOrderRefundCostService;
import com.yilin.tms.core.remote.IMessageRemote;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.core.remote.IVehicleRemote;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 运单仲裁Service
 *
 * @author zhangjinyuan
 * @date 2022/10/29
 */
@Service
@Transactional
public class SpecialApplyService extends ServiceImpl<SpecialApplyMapper, OrderSpecialApply> implements ISpecialApplyService {

    @Resource
    IOrderAutLogService orderAutLogService;
    @Resource
    IOrderRefundCostService orderRefundCostService;
    @Resource
    ITransitService transitService;
    @Resource
    IGoodsService goodsService;
    @Resource
    IRobService robService;

    @Resource
    IUserRemote userRemote;
    @Resource
    IVehicleRemote vehicleRemote;
    @Resource
    IMessageRemote messageRemote;
    @Resource
    IGpsRemote gpsRemote;

    /**
     * 申请仲裁和结算申述
     */
    @Override
    public void applyArbitration(Account loginUser, TransitOrder transitOrder, OrderSpecialApply orderSpecialApply) {
        orderSpecialApply.setSpecialStatus(OrderSpecialApply.SpecialStatus.processing);
        orderSpecialApply.setConfirmStatus(transitOrder.getTransitStatus());
        orderSpecialApply.setApplyPersonId(loginUser.getId());
        orderSpecialApply.setTransitOrderId(transitOrder.getId());
        orderSpecialApply.setTransitOrderNo(transitOrder.getTransportNo());
        orderSpecialApply.setApplyPersonName(loginUser.getName());
        orderSpecialApply.setApplyPersonPhone(loginUser.getPhone());
        orderSpecialApply.setApplyOrganizeId(loginUser.getOrganizeId());
        orderSpecialApply.setApplyOrganizeName(loginUser.getOrganizeName());
        if (loginUser.getUserType() == UserType.shipperUser) {
            orderSpecialApply.setBeArbitrationPersonId(transitOrder.getRobAccountId());
            orderSpecialApply.setBeArbitrationPersonName(transitOrder.getRobAccountName());
            orderSpecialApply.setBeArbitrationPersonPhone(transitOrder.getRobAccountPhone());
            orderSpecialApply.setBeArbitrationOrganizeId(transitOrder.getRobOrganizeId());
            orderSpecialApply.setBeArbitrationOrganizeName(transitOrder.getRobOrganizeName());
        } else {
            orderSpecialApply.setBeArbitrationPersonId(transitOrder.getShipperAccountId());
            orderSpecialApply.setBeArbitrationPersonName(transitOrder.getShipperAccountName());
            orderSpecialApply.setBeArbitrationPersonPhone(transitOrder.getShipperAccountPhone());
            orderSpecialApply.setBeArbitrationOrganizeId(transitOrder.getShipperOrganizeId());
            orderSpecialApply.setBeArbitrationOrganizeName(transitOrder.getShipperOrganizeName());
        }
        Organize organize= ParamUtil.isSuccess(userRemote.getOrganizeById(loginUser.getSuperiorPlatId()));
        if(orderSpecialApply.getPlatId()==null)orderSpecialApply.setPlatId(organize.getId());
        if(orderSpecialApply.getPlatName()==null)orderSpecialApply.setPlatName(organize.getOrganizeName());
        if(orderSpecialApply.getZonePlatId()==null)orderSpecialApply.setZonePlatId(organize.getSuperiorPlatOrganizeId());
        if(orderSpecialApply.getZonePlatName()==null)orderSpecialApply.setZonePlatName(organize.getSuperiorPlatOrganizeName());
        orderSpecialApply.setAddUserId(loginUser.getId());
        orderSpecialApply.setCreateTime(new Date());
        saveOrUpdate(orderSpecialApply);
        //保存订单打印日志
        orderAutLogService.saveTransitAutLog(transitOrder.getId(), loginUser, "【申请仲裁】", orderSpecialApply.getRemark());
        //更新订单状态
        TransitOrder localTransitOrder = transitService.getById(transitOrder.getId());
        localTransitOrder.setLockingStatus(TransitOrder.LockingStatus.locking);
        localTransitOrder.setUpdateUserId(loginUser.getId());
        localTransitOrder.setUpdateTime(new Date());
        transitService.saveOrUpdate(localTransitOrder);
        //更新被仲裁人信息
        String personId = orderSpecialApply.getBeArbitrationPersonId();
        userRemote.updateUserAccrual(personId, UserAccrual.arbitrationAccrual());
    }

    /**
     * 处理仲裁
     */
    @Override
    public void editSpecialApply(Account loginUser, OrderSpecialApply orderSpecialApply, OrderSpecialApply localOrderSpecialApply, TransitOrder transitOrder) {
        //处理备注保存操作日志需要
        String dealRemark = "";
        //通知短信需要
        boolean boolBack = false;
        if (orderSpecialApply.getProcessingResult() == OrderSpecialApply.ProcessingResult.noperation) {
            dealRemark = "【继续执行运单】";
            updateTransitOrder(loginUser, transitOrder, orderSpecialApply);
        }else if (orderSpecialApply.getProcessingResult() == OrderSpecialApply.ProcessingResult.reimburse) {
            dealRemark = "【销单并退款】";
            //TODO:创建退款单退款
            RobOrder robOrder = robService.getById(transitOrder.getRobOrderId());
            GoodsOrder goodsOrder = goodsService.getById(transitOrder.getGoodsOrderId());
            orderRefundCostService.generateTransitOrderRefund(transitOrder, robOrder, goodsOrder);
            boolBack = true;
            deleteTransitOrderAndVehicle(loginUser, transitOrder);
        } else if (orderSpecialApply.getProcessingResult() == OrderSpecialApply.ProcessingResult.singlepin) {
            dealRemark = "【直接销单】";
            deleteTransitOrderAndVehicle(loginUser, transitOrder);
        }
        //扣除信用分
        if (orderSpecialApply.getCredit() > 0) {
            String beAccountId = localOrderSpecialApply.getBeArbitrationPersonId();
            String reason = String.format("运单（%s）仲裁结果：%s，扣除信用分：%s",transitOrder.getTransportNo(),dealRemark, orderSpecialApply.getCredit());
            userRemote.updateUserCredit( beAccountId, -orderSpecialApply.getCredit(),reason);
        }
        localOrderSpecialApply.setProcessingResult(orderSpecialApply.getProcessingResult());
        localOrderSpecialApply.setDealtPersonId(loginUser.getId());
        localOrderSpecialApply.setDealtPersonName(loginUser.getName());
        localOrderSpecialApply.setIndemnity(orderSpecialApply.getIndemnity());
        localOrderSpecialApply.setDealtRemark(orderSpecialApply.getDealtRemark());
        localOrderSpecialApply.setCredit(orderSpecialApply.getCredit());
        localOrderSpecialApply.setProcessingTime(new Date());
        localOrderSpecialApply.setUpdateUserId(loginUser.getId());
        localOrderSpecialApply.setUpdateTime(new Date());
        localOrderSpecialApply.setSpecialStatus(OrderSpecialApply.SpecialStatus.complete);
        saveOrUpdate(localOrderSpecialApply);
        //保存订单操作日志
        orderAutLogService.saveTransitAutLog(transitOrder.getId(), loginUser, "【仲裁完成】", dealRemark);
        //发短信给双方账户
        String shipperRemake = "尊敬的用户您好，您的运单仲裁处理完成，仲裁结果：" + dealRemark + "，备注：" + localOrderSpecialApply.getDealtRemark();
        String truckRemake = shipperRemake;
        if (boolBack) shipperRemake += "，系统正在退还您已支付的运单费用，该费用将在7天内原路退还";
        messageRemote.sendPhoneMessage(localOrderSpecialApply.getApplyPersonPhone(), shipperRemake);
        messageRemote.sendPhoneMessage(localOrderSpecialApply.getBeArbitrationPersonPhone(), truckRemake);
    }

    /**
     * 内部 还原运单
     */
    private void updateTransitOrder(Account loginUser, TransitOrder transitOrder, OrderSpecialApply localOrderSpecialApply) {
        transitOrder.setLockingStatus(TransitOrder.LockingStatus.none);
        transitOrder.setTransitStatus(localOrderSpecialApply.getConfirmStatus());
        transitOrder.setUpdateUserId(loginUser.getId());
        transitOrder.setUpdateTime(new Date());
        transitService.saveOrUpdate(transitOrder);
    }

    /**
     * 内部 销单并更新车辆
     */
    private void deleteTransitOrderAndVehicle(Account loginUser, TransitOrder transitOrder) {
        transitOrder.setTransitStatus(TransitOrder.TransitStatus.scraped);
        transitOrder.setLockingStatus(TransitOrder.LockingStatus.none);
        transitOrder.setUpdateUserId(loginUser.getId());
        transitOrder.setUpdateTime(new Date());
        transitService.saveOrUpdate(transitOrder);
        ParamUtil.isSuccess(vehicleRemote.updateVehicleStatus(transitOrder.getTransitTruckId(), TruckVehicle.TruckStatus.unused));

        TruckVehicle vehicle = ParamUtil.isSuccess(vehicleRemote.getVehicleById(transitOrder.getTransitTruckId()));
//        if (vehicle.getPlatId().equals(transitOrder.getPlatId())){
//            if (vehicle.getTruckGpsType()== VehicleGps.TruckGpsType.hyb){
//                ParamUtil.isSuccess(gpsRemote.deleteStoreDevicePolygon(transitOrder.getPlatId(),transitOrder.getTransportNo()));
//            }
//        }

    }
}
